package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.MD5Utils;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberMobileController {
    @Reference
    private MemberService memberService;
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/login")
    public Result login(@RequestBody Map map, HttpServletResponse resp) throws Exception {
        Jedis resource = jedisPool.getResource();
        try {
            //获取用户输入的验证码和手机号
            String validateCode = (String) map.get("validateCode");
            String telephone = (String) map.get("telephone");
            String redisValidateCode = resource.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
            if (validateCode.equals(redisValidateCode)) {
                //通过手机号码查询是否已注册会员
                Member member = memberService.findByTel(telephone);
                //非会员自动注册
                if (member == null) {
                    member = new Member();
                    member.setRegTime(DateUtils.parseDate2String(new Date()));
                    member.setPhoneNumber(telephone);
                    memberService.add(member);
                } else {
                    //该手机号已注册会员,则将会员的信息保存到cookie中
                    Cookie cookie = new Cookie("telephone", telephone);
                    cookie.setPath("/");
                    cookie.setMaxAge(60 * 60 * 24 * 30);
                    //将响应添加Cookie
                    resp.addCookie(cookie);
                    //将会员信息转换为json类型
                    String json = JSON.toJSON(member).toString();
                    //将会员信息添加到redis中
                    resource.setex(telephone, 60 * 30, json);
                    //返回结果
                    return new Result(true, MessageConstant.LOGIN_SUCCESS);
                }
            }
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }finally {
            if (resource != null) {
                resource.close();
            }
        }


    }

    @RequestMapping("/loginByPwd")
    public Result loginByPwd(@RequestBody Map map, HttpServletResponse resp) {
        //获取用户输入的手机号和密码
        String telephone = (String) map.get("telephone");
        String password = (String) map.get("password");
        //通过手机号码和密码查询
        Member member = memberService.findByTelAndPassword(map);
        if (member != null) {

            Cookie cookie = new Cookie("telephone", telephone);
            Cookie cookie1 = new Cookie("password", MD5Utils.md5(password));
            cookie.setPath("/");
            cookie.setMaxAge(60 * 60 * 24 * 30);
            //将响应添加Cookie
            resp.addCookie(cookie);
            resp.addCookie(cookie1);
            //将会员信息转换为json类型
            String json = JSON.toJSON(member).toString();
            //将会员信息添加到redis中
            Jedis resource = jedisPool.getResource();
            resource.setex(telephone, 60 * 30, json);
            resource.close();
            //返回结果
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }
        return new Result(false, MessageConstant.LOGIN_FAIL_PASSWORD);
    }

    @RequestMapping("/editPwdByTel")
    public Result editPwdByTel(@RequestParam String phoneNum, @RequestParam String password, HttpServletRequest request) {
        try {
            boolean flag = judgeLogin(request);
            if (flag == false) {
                return new Result(false, MessageConstant.LOGIN_STATE);
            } else {
                Member member = memberService.findByTel(phoneNum);
                if (member != null) {
                    member.setPassword(password);
                    memberService.editByTel(member);
                    return new Result(true, MessageConstant.EDIT_PWD_SUCCESS);
                }
                return new Result(false, MessageConstant.EDIT_PWD_FAIL);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_PWD_FAIL1);
        }
    }

    @RequestMapping("/editTelByPwd")
    public Result editTelByPwd(@RequestParam String phoneNum, @RequestParam String password, HttpServletRequest request) {
        try {
            boolean flag = judgeLogin(request);
            if (flag == false) {
                return new Result(false, MessageConstant.LOGIN_STATE);
            } else {
                Cookie[] cookies = request.getCookies();
                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        if ("telephone".equals(cookie.getName())) {
                            String telephone = cookie.getValue();
                            Member member = memberService.findByTel(telephone);
                            if (password.equals(member.getPassword())) {
                                member.setPhoneNumber(phoneNum);
                                memberService.editByTel(member);
                                return new Result(true, MessageConstant.EDIT_PHONE_SUCCESS);
                            }
                        }

                    }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_PHONE_FAIL);
        }
        return new Result(false, MessageConstant.EDIT_PHONE_FAIL);
    }

    public boolean judgeLogin(HttpServletRequest request) {
        boolean flag = false;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("telephone".equals(cookie.getName())) {
                    flag = true;
                }
                }
            }
        return flag;

        }
    }
